package com.wzt.lianfirecontrol.fragment.xiaokongshi;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.xiaokongshi.DutyListAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XiaoKongShiModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XksRecordModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * 消控室值班列表
 */
public class DutyListFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener, DutyListAdapter.DutyCallBack {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_info_list;
    private BaseRecyclerAdapter baseRecyclerAdapter;
    private LinearLayoutManager llm_info_list;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;


    private static final int INFO_LIST_REQUEST_WHAT = 0;
    private static final int RECORD_DETAIL_REQUEST_WHAT = 1;

    private XksRecordModel xksRecordModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_info_list, container, false);
            initView();

            UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
            if (!userInfoModel.getRoleAlias().contains(RoleConstant.ROLE_DUTY)) {
                ToastUtils.showToast(activity, "非值班员用户");
            }
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));

        initListView();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });

        if (activity instanceof ShowFragActivity && !(getParentFragment() instanceof DutyHistoryFragment)){
            BannerModel bannerModel = new BannerModel();
            bannerModel.setTitle("历史");
            bannerModel.setActionTitle("值班历史");
            bannerModel.setActionType(ConstData.SHOWFRAG);
            bannerModel.setActionValue(ConstData.DUTYHISTORY);
            Bundle bundle = new Bundle();
            ((ShowFragActivity)activity).setTextEtAction(bannerModel, bundle);
        }
    }

    private void initListView() {
        rlv_info_list = itemContentView.findViewById(R.id.rlv_info_list);
        llm_info_list = new LinearLayoutManager(activity);
        llm_info_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_info_list.setLayoutManager(llm_info_list);

        baseRecyclerAdapter = new DutyListAdapter(activity, this);
        rlv_info_list.setAdapter(baseRecyclerAdapter);
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
    }

    /**
     * 获取列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> url_params = new HashMap<>();
        url_params.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(url_params));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XKS_LIST_URL, INFO_LIST_REQUEST_WHAT, handler, true, hashMap);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }


    /**
     * 获取记录详情
     */
    private void initRecordDetailHttpHelper(String id) {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> url_params = new HashMap<>();
        url_params.put("id", id);

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(url_params));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XKS_RECORD_DETAIL_URL, RECORD_DETAIL_REQUEST_WHAT, handler, true, hashMap);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }

    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what){
                    case INFO_LIST_REQUEST_WHAT:
                        LinkedList<XiaoKongShiModel> deviceListModels = (LinkedList<XiaoKongShiModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(dataStr), XiaoKongShiModel.class);
                        bundle.putSerializable("list", deviceListModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case RECORD_DETAIL_REQUEST_WHAT:
                        XksRecordModel xksRecordModel = JSONUtil.jsonObjectToBean(new JSONObject(dataStr), XksRecordModel.class);
                        bundle.putSerializable("data", xksRecordModel);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                bundle.putBoolean(REQUEST_OK, false);
                bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            if (msg.what == INFO_LIST_REQUEST_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }
            if (msg.what == RECORD_DETAIL_REQUEST_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }
            return;
        }
        switch (msg.what){
            case INFO_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<XiaoKongShiModel>)bundle.getSerializable("list"));
                break;
            case RECORD_DETAIL_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setRecordClickACtion((XksRecordModel) bundle.getSerializable("data"));
                break;
        }
    }

    private void setListData(LinkedList<XiaoKongShiModel> list) {
        baseRecyclerAdapter.clear();
        if (null == list || list.size() == 0) {

            include_no_data.setVisibility(View.VISIBLE);
            return;
        }
        include_no_data.setVisibility(View.GONE);
        baseRecyclerAdapter.addDatas(list);
    }

    /**
     * 确认状态后列表点击动作
     * @param model
     */
    private void setRecordClickACtion(XksRecordModel model) {
        xksRecordModel.setStatus(model.getStatus());
        xksRecordModel.setRecordItems(model.getRecordItems());
        xksRecordModel.setRecordProblems(model.getRecordProblems());
        xksRecordModel.setRecordUsers(model.getRecordUsers());
        xksRecordModel.setEquImgs(model.getEquImgs());
        xksRecordModel.setSignImg(model.getSignImg());
        if (!UserInfoModel.isSelfCompany(activity)){
        //    ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
            return;
        }
        BannerModel bannerModel = new BannerModel();
        bannerModel.setActionTitle(xksRecordModel.getRoomName());
        bannerModel.setActionType(ConstData.SHOWFRAG);
        Bundle bundle = new Bundle();
        switch(xksRecordModel.getStatus()) {
            case "1":// 待值班
                try {
                    String startTime = xksRecordModel.getClassStartTimeStr();// 2020-06-14 06:00
                    Date date = new Date();// 当前时间
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ConstData.TIME_FORMAT_YYYY_MM_DD_HH_MM);
                    Date startDate = simpleDateFormat.parse(startTime);
                    if (date.before(startDate)) {
                        ToastUtils.showToast(activity, "未到时间");
                    } else {
                        bannerModel.setActionValue(ConstData.BARFLOOR);
                        bundle.putString(ConstData.BARTYPE, "1");
                        bundle.putSerializable("XksRecordModel", xksRecordModel);
                        activity.setClickAction(bannerModel, bundle);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "2":// 值班中
                bannerModel.setActionValue(ConstData.BARFLOOR);
                bundle.putString(ConstData.BARTYPE, "1");
                bundle.putSerializable("XksRecordModel", xksRecordModel);
                activity.setClickAction(bannerModel, bundle);
                break;
            case "3":// 未值班
                ToastUtils.showToast(activity, "值班时间已过");
                break;
            case "4":// 待交接
            case "5":// 已完成
                bannerModel.setActionValue(ConstData.DUTYDETAIL);
                bundle.putSerializable("XksRecordModel", xksRecordModel);
                activity.setClickAction(bannerModel, bundle);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateData();
    }

    /**
     * 消控室值班项点击动作
     */
    @Override
    public void itemClick(XksRecordModel xksRecordModel) {
        if (null != include_progress_bar && include_progress_bar.getVisibility() == View.VISIBLE){
            return;
        }
        if ("3".equals(xksRecordModel.getStatus())){
            // 未值班
            ToastUtils.showToast(activity, "值班时间已过");
            return;
        }
        this.xksRecordModel = xksRecordModel;
        // 请求详情确认状态
        initRecordDetailHttpHelper(xksRecordModel.getId());
    }
}
